package com.example.nettydemo.tcpserver;

import com.example.nettydemo.handler.VoIpTcpServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * Author: wujing
 * Date:   2025/5/13 22:25
 * Description:VOIP
 * https://www.cnblogs.com/binbingg/p/18235704
 */
public class VoIpTcpServer {

    private int port;
    
    public VoIpTcpServer(int port) {
        this.port = port;
    }
    
    
    public void run() throws InterruptedException{
        // 创建线程池,用于处理服务器的接受连接请求
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        // 创建线程池,用于处理已经接受的连接,包括读取数据、处理数据和发送数据
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            // 创建服务器启动对象
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(io.netty.channel.socket.nio.NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer(){

                        @Override
                        protected void initChannel(Channel channel) {
                            // 设置自定义通道消息处理器
                            channel.pipeline().addLast(new StringDecoder(), new StringEncoder(),new VoIpTcpServerHandler());
                        }
                    })
                    .option(io.netty.channel.ChannelOption.SO_BACKLOG, 128)//设置服务器可以挂起未处理的连接的数量
                    .childOption(io.netty.channel.ChannelOption.SO_KEEPALIVE, true);//设置保持活动连接状态
            // 绑定服务器监听端口, 同步等待成功
            ChannelFuture future = bootstrap.bind(port).sync();

            //打印服务器启动信息
            System.out.println("Server started on port " + port);

            // 开启通道监监听器，监听通道是否关闭
            future.channel().closeFuture().sync();
        }finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }

    }
}
